/*
 * @Author: 罗顺枫 shunfeng.luo@deepfinance.com
 * @FilePath: \cine-rate\client\src\index.js
 * @Date: 2023-12-04 09:56:49
 * @Description: 
 */
import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import ReactDOM from 'react-dom/client';
import { Auth0Provider, useAuth0 } from "@auth0/auth0-react";
import { AuthTokenProvider } from "./AuthTokenContext";
import AppLayout from './components/AppLayout';
import VerifyUser from './components/VerifyUser';
import Login from './components/Login';
import MovieList from './components/MovieList';
import MovieDetail from './components/MovieDetail';
import OuterApiPage from './components/OuterApiPage';
import AuthDebugger from './components/AuthDebugger';
import Profile from './components/Profile';
import NotFound from './components/NotFound';
import "./style/normalize.css";
import "./style/index.css";

const requestedScopes = ["profile", "email"];

const root = ReactDOM.createRoot(document.getElementById('root'));


function RequireAuth({ children }) {
  const { isAuthenticated, isLoading } = useAuth0();

  // If the user is not authenticated, redirect to the Login page
  if (!isLoading && !isAuthenticated) {
    return <Navigate to="/" replace />;
  }

  // Otherwise, display the children (the protected page)
  return children;
}

root.render(
  <React.StrictMode>
    <Auth0Provider
      domain={process.env.REACT_APP_AUTH0_DOMAIN}
      clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: `${window.location.origin}/verify-user`,
        audience: process.env.REACT_APP_AUTH0_AUDIENCE,
        scope: requestedScopes.join(" "),
      }}
    >
      <AuthTokenProvider>
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<Login />} />
            <Route path="/verify-user" element={<VerifyUser />} />
            <Route
              path="app"
              element={
                <RequireAuth>
                  <AppLayout />
                </RequireAuth>
              }
            >
              <Route index path="movieList" element={<MovieList />} />
              <Route path="profile" element={<Profile />} />
              <Route path="movieDetail/:movieId" element={<MovieDetail />} />
              <Route path="debugger" element={<AuthDebugger />} />
              <Route path="outerPage" element={<OuterApiPage />} />
            </Route>
            <Route path="*" element={<NotFound />} />
          </Routes>
        </BrowserRouter>
      </AuthTokenProvider>
    </Auth0Provider>
  </React.StrictMode>
);
